# -*- coding:utf-8 -*-
# get hardware message

import os
import re
import inspect


class GetHardwareMessage(object):

    def __init__(self):
        if os.popen('rpm -q facter &>/dev/null; echo $?').read().strip() == '1':
            os.system('yum install facter')
        if os.popen('rpm -q dmidecode &>/dev/null;echo $?').read().strip() == '1':
            os.system('yum install dmidecode')

        # init base massege saved in facter{}
        self.facter = {}
        for line in os.popen('facter'):
            line_list = line.split('=>')
            self.facter[line_list[0].strip()] = line_list[1].strip()

    # check if init dict informations has not in the facter massage then put '_'  else put the information to date dict
    def __handlerFacter__(self,items,inputdata,data):
        for k,v in items.items():
            if not k in inputdata.keys():
                data[v]='-'
            else:
                data[v]=inputdata[k]
        return data

    def get_cpu(self):
        cpu={}
        # init a dict for cpu informations
        items = {'processor0':'model','physicalprocessorcount':'core','processorcount':'thread'}
        cpu = self.__handlerFacter__(items,self.facter,cpu)
        cpu['frequency']=os.popen('lscpu | grep MHz').read().split(":")[1].strip()+'MHz'
        return cpu

    def get_memory(self):
        memory=[]
        memory_temp_data = {}
        for line in  os.popen('dmidecode -t memory'):
            if not re.match('^(Handle|Memory|Physical)',line):
                line=line.strip()
                if line:
                    line = line.split(':')
                    try:
                        memory_temp_data[line[0].strip()]=line[1].strip()
                    except IndexError:
                        pass
                if not line:
                    if "Size" in memory_temp_data.keys() and memory_temp_data['Size'] != 'No Module Installed':
                        items={'Speed':'speed','Configured Clock Speed':'configSpeed',
                               'Type':'type','Serial Number':'serial','Size':'size'}
                        data = {}
                        memory.append(self.__handlerFacter__(items,memory_temp_data,data))
                    memory_temp_data = {}
        return memory

    def get_network(self):
        network = []
        for item in self.facter['interfaces'].strip().split(','):
            if not re.match('^(v.*|lo.*)',item):
                data = {}
                item = item.replace("_",":")
                data['interface'] = item
                for flag in ['mac','ip','speed','statu']:
                        data[flag]='-'
                for line in os.popen('ifconfig %s | egrep "HWaddr|inet "' % item):
                    if line.find('HWaddr')!= -1:
                        data['mac'] = line.strip().split()[4]
                    if line.find('inet ') != -1:
                        ip = line.strip().split()[1]
                        ip = ip[ip.find(":")+1:]
                        data['ip'] = ip
                for line in os.popen('ethtool %s' % item):
                    if line.find('Speed')!=-1:
                        data['speed'] = line.split(':')[1].strip()
                    if line.find('Link detected') != -1:
                        data['statu'] = line.split(':')[1].strip()
                network.append(data)
        return network

    def get_partition(self):
        partition=[]
        for line in os.popen('df -Ph'):
            data = {}
            if re.match('^/.*',line):
                line_list = line.strip().split()
                data['file_system'] = line_list[0]
                data['mount_point'] = line_list[5]
                data['total_size'] = line_list[1]
                data['usage_size'] = line_list[2]
                partition.append(data)
        return partition

    def get_main(self):
        main = {}
        items = {'fqdn':'hostname','ipaddress':'main_ip',
                 'memorytotal':'memory_total_size','memoryfree':'memory_free_size',
                 }
        main = self.__handlerFacter__(items,self.facter,main)
        size = 0
        for line in os.popen('fdisk -l 2>/dev/null| grep "^Disk" | grep -v "ident" | grep -v "mapper"'):
            size += float(line.split()[2].strip())
        main['disk_total_size'] = size
        return main

    def get_platform(self):
        platfrom={}
        items = {'boardmanufacturer':'vendor',
                 'productname':'model','boardserialnumber':'serial',
                 'architecture':'arch','virtual':'virtual','kernelrelease':'kernel'}
        platfrom = self.__handlerFacter__(items,self.facter,platfrom)
        os = self.facter['operatingsystem']+self.facter['operatingsystemrelease']
        platfrom['os']=os
        return platfrom


    def run_all_get(self):
        self.sendData = {}
        for fun in (inspect.getmembers(self, predicate=inspect.ismethod)):
            # fun[0] is the name of method, fun[1] is the object of the method
            if fun[0][:3] == "get":
                # fun[0][4:] is the valuname ,fun[1]() to exec the method
                self.sendData[fun[0][4:]] = fun[1]()
        return self.sendData


if __name__ == "__main__":
    base_message = GetHardwareMessage()
    # print base_message.facter
    print base_message.run_all_get()